package exception.SpringException;

import util.ResponseBean;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import util.ParameterUtils;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.Set;

@ControllerAdvice
public class DiyException {

    @Resource
    private ResponseBean responseBean;

    @ExceptionHandler(value = ValidationException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseBean validation(ValidationException exception) {
        responseBean.setAll(ResponseBean.HTTP_CODE_BAD_REQUEST, ResponseBean.MSG_PARAMETER_ERROR_MESSAGE, null);

        //此处待定,后续可能切换为快速模式(目前为普通校验模式)
        if (exception instanceof ConstraintViolationException) {
            ConstraintViolationException exs = (ConstraintViolationException) exception;
            Set<ConstraintViolation<?>> violations = exs.getConstraintViolations();
            for (ConstraintViolation<?> item : violations) {
                System.out.println(item.getMessage());
            }
        }
        return responseBean;
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseBean diyException(Exception exception) {
        responseBean.setAll(ResponseBean.HTTP_CODE_SYSTEM_ERROR, ResponseBean.MSG_SYSTEM_ERROR_MESSAGE, null);
        exception.printStackTrace();
        return responseBean;
    }

    @ExceptionHandler(value = DataIntegrityViolationException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseBean diyDataIntegrityViolationException(Exception exception) {
        //以null方式插入非null字段,这儿出问题根源：自身逻辑或数据库更改
        responseBean.setAll(ResponseBean.HTTP_CODE_SYSTEM_ERROR, ResponseBean.MSG_SYSTEM_ERROR_MESSAGE, null);
        exception.printStackTrace();
        return responseBean;
    }


}
